<?php

namespace app\model;

use think\Model;
use think\facade\Cache;
use think\facade\Db;

class ProjectModel extends Model
{
    protected $table = 'projects';

    // 关联项目的管理员
    public function admin()
    {
        return $this->belongsTo(UserModel::class, 'admin_id');
    }

    // 关联项目的教师
    public function teachers()
    {
        return $this->belongsToMany(UserModel::class, 'project_teachers', 'project_id', 'teacher_id');
    }

    // 关联项目的技能
    public function skills()
    {
        return $this->hasMany(Skill::class, 'project_id');
    }

    // 关联项目的荣誉
    public function honors()
    {
        return $this->hasMany(HonorModel::class, 'project_id');
    }

    // 数据验证
    public static function validateData($data)
    {
        $validate = new \think\Validate([
            'name' => 'require|unique:projects|max:255',
            'description' => 'require|max:500',
        ]);

        return $validate->check($data);
    }

    // 在项目创建时自动设置创建时间和更新时间
    protected static function init()
    {
        self::event('before_insert', function ($project) {
            $project->created_at = $project->updated_at = time();
        });
    }

    // 获取项目缓存
    public static function getProjectByIdWithCache($id)
    {
        $cacheKey = 'project_' . $id;
        $project = Cache::get($cacheKey);
        if (!$project) {
            $project = self::find($id);
            Cache::set($cacheKey, $project, 3600);  // 缓存1小时
        }
        return $project;
    }
}
